package org.jpass.dc.common.email;

import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.jpass.dc.common.util.Encrypter;

public class GenerateVelocityMail {
	private static final long serialVersionUID = 1L;

	/**
	 * 获取模板邮件内容
	 * */
	public String getContent(String emailFlag, String httpPath, String rootPath, String username, String sendEmailTime){
		VelocityEngine ve = new VelocityEngine();
		Properties prop = new Properties();
		prop.setProperty(Velocity.ENCODING_DEFAULT, "utf-8");
		prop.setProperty(Velocity.INPUT_ENCODING, "utf-8");
		prop.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");
		prop.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, rootPath + "res/email/");//邮件模板路径
		ve.init(prop);
		VelocityContext context = new VelocityContext();
		String actionPath="";
		if("register".equals(emailFlag)){
			try {
				actionPath = httpPath + "daycodefront/activate?method=activate&username=" + username + "&token=" + URLEncoder.encode(Encrypter.md5Encrypt(username),"UTF-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if("forgetPass".equals(emailFlag)){
			try {
				actionPath = httpPath + "daycodefront/updatePass?method=updatePass&username=" + username + "&token=" + URLEncoder.encode(Encrypter.md5Encrypt(username),"UTF-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		context.put("actionPath", actionPath);
		context.put("username", username);
		context.put("sendEmailTime", sendEmailTime);
		Template t = null;
		if("register".equals(emailFlag)){
			t = ve.getTemplate( "emailActivate.vm" );
		}else if("forgetPass".equals(emailFlag)){
			t = ve.getTemplate( "emailForgetPass.vm" );
		}
		StringWriter writer = new StringWriter();
		t.merge( context, writer );
		return writer.toString();
	}
}

